package com.example.wanxiang.service.Impl;

import com.example.wanxiang.dto.ChatDto;
import com.example.wanxiang.entity.Chat;
import com.example.wanxiang.repository.ChatRepository;
import com.example.wanxiang.service.ChatService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ChatImpl implements ChatService {

    @Resource
    private ChatRepository chatRepository;


    //保存聊天
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Chat createChat(Chat chat) {
        return chatRepository.save(chat);
    }

    //删除聊天
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteChat(String sponsor) {
        chatRepository.deleteBySponsor(sponsor);
    }

    //    查询所有聊天
    @Override
    public List<Chat> getAllChats() {
        return chatRepository.findAll();
    }

    //    通过Sponsor查询聊天
    @Override
    public List<Chat> getChatBySponsor(ChatDto chatDto) {
        PageRequest request = getRequest(chatDto);
        return getChatsList(chatRepository.getChatBySponsor(chatDto.getId(), request));
    }

    //    查询数量
    @Override
    public long getChatCount(ChatDto chatDto) {
        return chatRepository.countChatBySponsor(chatDto.getSponsor());
    }

    public PageRequest getRequest(ChatDto chatDto) {
        return PageRequest.of((int) chatDto.getPage(), (int) chatDto.getSize());
    }

    public List<Chat> getChatsList(Page<Chat> chats) {
        List<Chat> chats1 = new ArrayList<Chat>();

        for (Chat chat : chats) {
            chats1.add(chat);
        }
        return chats1;
    }

}
